<template>
	<div>
		<el-dialog
			title="分配权限"
			:visible.sync="allotRightsVisible"
			width="50%"
			:before-close="handleClose"
			@close="DialdgClose"
		>
			<el-tree
				:data="treedata"
				show-checkbox
				default-expand-all
				node-key="id"
				ref="tree"
				highlight-current
				:props="defaultProps"
			></el-tree>
			<span slot="footer" class="dialog-footer">
				<el-button @click="allotRightsVisible=false">取消</el-button>
				<el-button type="primary" @click="allotRights">确定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
export default {
	props: {
		//控制弹框的打开关闭
		allotRightsVisible: {
			type: Boolean,
			default: false
		},
		roleid: {
			type: parseInt,
			default: 0
		}
	},
	data() {
		return {
			treedata: [],
			defaultProps: {
				children: 'children',
				label: 'label'
			}
		}
	},
	methods: {
		DialdgClose() {
			//关闭弹框时触发
            console.log('关闭')
            this.$refs.tree.setCheckedKeys([]);
		},
		handleClose(done) {
			this.$confirm('确认关闭？')
				.then(_ => {
					done()
				})
				.catch(_ => {})
		},
		//初始化权限
		getRights() {
			this.$get('/api/Function/GetFunctionTree', {})
				.then(res => {
					if (res.code == 0) {
                        this.treedata = res.data
                        console.log(this.treedata)
                    }
                    this.$get('/api/Role/GetFunctionChildCodes',{roleid:this.roleid}).then(wres=>{
                        if(wres.code==0){
                            console.log(wres.data)
                            this.$refs.tree.setCheckedKeys(wres.data);
                        }
                    }).catch(werr=>{
                        console.msg(werr)
                    })
				})
				.catch(err => {
					console.log(err)
				})
        },
        //提交
        allotRights(){
            console.log(this.$refs.tree.getCheckedKeys());
            if(this.$refs.tree.getCheckedKeys().length == 0){
                this.$message("请选择")
                return;
            }
            let data={
                Fcodes:this.$refs.tree.getCheckedKeys().join(','),
                roleid:this.roleid
            }
            this.$get('/api/Role/AllotFunction',data).then(res=>{
                if(res.code==0){
                    this.$message({
                        message:res.msg,
                        type:'success'
                    })
                    this.allotRightsVisible=false;
                }else{
                    this.$message.error(res.msg)
                }
            }).catch(err=>{
                console.log(err)
            })
        }
	},
	watch: {
		allotRightsVisible: function(val) {
			let data = {
				IsShow: val
			}
			if (val == true) {
				this.getRights()
			}
			this.$emit('IsallotRights', data)
		}
	}
}
</script>